package com.config;

import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.model.User;
import com.service.UserService;
import com.utils.JwtUtils;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.filter.GenericFilterBean;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 请求拦截，验证jwt
 */
public class TokenFilter extends GenericFilterBean {
//    @Resource
//    private UserService userService;
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //1.获取jwt
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String authToken = request.getHeader("authToken");
        if (authToken==null||authToken.isEmpty()){
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }
        String username;
        // 2.验证JWT签名
        try{
            DecodedJWT jwt = JwtUtils.verify(authToken);
            username = jwt.getClaim("username").asString();
        }catch (JWTVerificationException e){
            PrintWriter writer = servletResponse.getWriter();
            writer.write("token认证错误，请重新登录");
            writer.flush();
            writer.close();
            return;
        }
        // 3.将认证信息放进上下文,否则仍会跳转到登录链接
        //User user = userService.loadUserByUsername(username);
        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, null,null);
        SecurityContextHolder.getContext().setAuthentication(token);
        filterChain.doFilter(servletRequest,servletResponse);

    }
}
